module(..., package.seeall)
----------------------------------------------------------------------------------
--
-- scenetemplate.lua
--
----------------------------------------------------------------------------------

local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local ui = require("ui")
local gui = require "Stage8.Stage8HomeGui".new()
local wEasing = require "wEasing"

----------------------------------------------------------------------------------
-- 
--	NOTE:
--	
--	Code outside of listener functions (below) will only be executed once,
--	unless storyboard.removeScene() is called.
-- 
---------------------------------------------------------------------------------

---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- Called when the scene's view does not exist:
function scene:createScene( event )
	local mainGroup = self.view

------------------------------------------------------------
local backgroundGroup,stageButtonGroup,homeButtonGroup,generateItemsGroup
local bg,replayButton,leftButton,centerButton,rightButton
local okImage,goodImage,perfectImage
local backgroundButton = {}

local itemEachTurn = 5
local imageItems,dishSupport = {},{}

local totalTimer
local totalTime,readyTime = 60000,4000
local deltaTotalTime

local _tran
local ySmallest = 50
local timeTransition = 100
local isFirstTouch = false
local tFormer
local xBiggest = 270
local _score
-----------------------------------------------------------------------------
function init()
	_score = {40,35,30,25,20}
	deltaTotalTime = totalTime + 1000
	generateItem(itemEachTurn)
	Runtime:addEventListener("enterFrame",onEnterFrame)
	for k,v in pairs(backgroundButton)do
		v:addEventListener("touch",onTouchMoveButton)
	end
	totalTimer = timer.performWithDelay(100,manageTotalTimer,0)
end
--------------------------- create group -------------------------------
	backgroundGroup = display.newGroup()
	stageButtonGroup = display.newGroup()
	homeButtonGroup = display.newGroup()
	generateItemsGroup = display.newGroup()
	
--------------------------------------------------------------------
-------------------------- handle function ------------------------------
function manageTotalTimer()
	deltaTotalTime = deltaTotalTime - 100
	if(deltaTotalTime < totalTime + readyTime and deltaTotalTime >= totalTime +1000)then
		readyText.alpha = 1
		readyText.text = math.round((deltaTotalTime-totalTime)/1000)
	elseif(deltaTotalTime < totalTime +1000 and deltaTotalTime >= totalTime)then
		goText.alpha = 1
		readyText.alpha = 0
	elseif(deltaTotalTime < totalTime)then
		goText.alpha = 0
		
	end
end

function generateItem(itemEachTurn)
	-- for i = 1,3,1 do
		-- dishSupport[i] = display.newImageRect(stageButtonGroup,gui.dishSupport.fn,gui.dishSupport.w,gui.dishSupport.h)
			-- dishSupport[i].x = gui.dishSupport.x[i]
			-- dishSupport[i].y = gui.dishSupport.y[i]
			-- dishSupport[i].id = i
	-- end
	for i = 1,itemEachTurn,1 do
		imageItems[i] = display.newImageRect(generateItemsGroup, gui.imageItems.fn[i], gui.imageItems.w*(100-10*i)/100, gui.buttonPosition.h*(100-10*i)/100)
			imageItems[i].x = gui.imageItems.x
			imageItems[i].y = gui.imageItems.y - 20*(i-1)
			imageItems[i].id = i
			imageItems[i].light =false
			-- imageItems[i].alpha = 0
	end
end

function onTouchMoveButton(event)
	local t = event.target
	local phase = event.phase
	if(phase == "began")then
		if(isFirstTouch == false)then
			isFirstTouch = true
			tFormer =system.getTimer()
			print(tFormer)
		end
		local newImage
		local itemToMove = checkItemInHigh(ySmallest)
		local smallestDish = findSmallestDish(t.x)
		if(itemToMove ~= 0 and itemToMove ~= nil)then
		if(smallestDish ~= nil and itemToMove.width > smallestDish.width)then
				return
		end
		if(smallestDish ~= nil)then
			-- newImage = display.newImageRect(generateItemsGroup,gui.imageItems.fn,itemToMove.width,itemToMove.height)
				-- newImage.x = itemToMove.x
				-- newImage.y = itemToMove.y
				-- newImage.id = itemToMove.id
				-- newImage.light = false
				-- newImage.alpha = 0
			for k,v in pairs(imageItems)do
				if(v == itemToMove)then
					-- display.remove(v)
					-- v = nil
					-- imageItems[k] = newImage
					imageItems[k].alpha = 0.5
					v.light = false
				end
			end
			if(_tran == nil)then
				_tran = transition.to(itemToMove,{time = timeTransition, alpha = 1, x = t.x, y = smallestDish.y -20, 
				onStart = onStartTransition, onComplete = onFinishTransition })
			else
				transition.cancel(_tran)
				_tran = transition.to(itemToMove,{time = timeTransition, alpha = 1, x = t.x, y = smallestDish.y-20, 
				onStart = onStartTransition, onComplete = onFinishTransition })
			end
		else
			-- newImage = display.newImageRect(generateItemsGroup,gui.imageItems.fn,itemToMove.width,itemToMove.height)
				-- newImage.x = itemToMove.x
				-- newImage.y = itemToMove.y
				-- newImage.id = itemToMove.id
				-- newImage.light = false
				-- newImage.alpha = 0
			for k,v in pairs(imageItems)do
				if(v == itemToMove)then
					-- display.remove(v)
					-- v = nil
					-- imageItems[k] = newImage
					imageItems[k].alpha = 0.7
					v.light = false
				end
			end
			if(_tran == nil)then
				_tran = transition.to(itemToMove,{time = timeTransition, alpha = 1, x = t.x, y = gui.imageItems.y, 
				onStart = onStartTransition, onComplete = onFinishTransition })
			else
				transition.cancel(_tran)
				_tran = transition.to(itemToMove,{time = timeTransition, alpha = 1, x = t.x, y = gui.imageItems.y, 
				onStart = onStartTransition, onComplete = onFinishTransition })
			end
		end
		
	elseif(smallestDish ~= nil)then
	
		-- newImage = display.newImageRect(generateItemsGroup,gui.lightImageItems.fn,smallestDish.width,smallestDish.height)
			-- newImage.x = smallestDish.x
			-- newImage.y = smallestDish.y
			-- newImage.id = smallestDish.id
			-- newImage.light = true
			-- newImage.alpha = 0
		for k,v in pairs(imageItems)do
			if(v == smallestDish)then
				-- display.remove(v)
				-- v = nil
				-- imageItems[k] = newImage
				imageItems[k].alpha = 0.7
				v.light = true
			end
		end
		
		-- if(_tran == nil)then
			-- _tran = transition.to(smallestDish,{time = timeTransition, alpha = 1, x = t.x, y = ySmallest, 
			-- onStart = onStartTransition, onComplete = onFinishTransition })
		-- else
			-- transition.cancel(_tran)
			-- _tran = transition.to(smallestDish,{time = timeTransition, alpha = 1, x = t.x, y = ySmallest, 
			-- onStart = onStartTransition, onComplete = onFinishTransition })
		-- end
		else
			-----------------------  no item to move -------------------------
		end
	end
end

function findSmallestDish(xPosition)
	local itemToMove = nil
	for k,v in pairs(imageItems)do
		if(v.x == xPosition and v.y ~= ySmallest and v.light ~= true)then
			if(itemToMove ~= nil)then
				if(itemToMove.width > v.width)then
					itemToMove = v
				end
			else itemToMove = v
			end
		end
	end
	return itemToMove
end

function checkItemInHigh(yPosition)
	for k,v in pairs(imageItems)do
		if(v.light == true)then
			return v
		end
	end
	return 0
end

function onStartTransition()
	for k,v in pairs(backgroundButton)do
		v:removeEventListener("touch",onTouchMoveButton)
	end
end
function onFinishTransition()
	for k,v in pairs(backgroundButton)do
		v:addEventListener("touch",onTouchMoveButton)
	end
end

function onEnterFrame()
	if(checkWin())then
		timeScore = system.getTimer() - tFormer
		
		timer.cancel(totalTimer)
		Runtime:removeEventListener("enterFrame",onEnterFrame)
		-- for k,v in pairs(backgroundButton)do
			-- v:removeEventListener("touch",onTouchMoveButton)
		-- end
		-- goText.text = "Win"
		-- goText.alpha = 1
		
		-- print(timeScore)
		local temp,star
		temp = math.round(timeScore/100)/10
		if(temp <= 20)then
			star = 5
		elseif(temp > 20 and temp <= 25)then
			star = 4
		elseif(temp > 25 and temp <= 30)then
			star = 3 
		elseif(temp > 30 and temp <= 35)then
			star = 2
		elseif(temp > 35 and temp <= 40)then
			star = 1
		else star = 0
		end
		local g1
		g1 = require "popup.popupWin".new(temp,star,_score,onReplayButtonTap)
		transition.to(g1,{time = 200,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic})
	end
end

function onReplayButtonTap()
	Runtime:removeEventListener("enterFrame",onEnterFrame)
	for k,v in pairs(imageItems)do
		display.remove(v)
		v = nil
		k = nil
	end
	for k,v in pairs(backgroundButton)do
		v:removeEventListener("touch",onTouchMoveButton)
	end
	if(totalTimer ~= nil)then
		timer.cancel(totalTimer)
	end
	
	init()
end

function checkWin()
	for k,v in pairs(imageItems)do
		if(v.x ~= xBiggest)then
			return false
		end
	end
	return true
end

function onStartPopup()
	timer.pause(totalTimer)
end

function onResumeFromPopup()
	timer.resume(totalTimer)
end

do -------------------- background and button ---------------------
bg = display.newImageRect(backgroundGroup, gui.bg.fn, gui.bg.w, gui.bg.h)
	bg.x = gui.bg.x
	bg.y = gui.bg.y

replayButton = ui.newButton({
	defaultSrc = gui.replayButton.fn,
	overSrc = gui.replayButton.fn,
	defaultX = gui.replayButton.w,
	defaultY = gui.replayButton.h,
	overX = gui.replayButton.w,
	overY = gui.replayButton.h,
	x = gui.replayButton.x,
	y = gui.replayButton.y,
	
	onRelease = onReplayButtonTap
})
homeButtonGroup:insert(replayButton)

pauseButton = ui.newButton({
	defaultSrc = gui.pauseButton.fn,
	overSrc = gui.pauseButton.fn,
	defaultX = gui.pauseButton.w,
	defaultY = gui.pauseButton.h,
	overX = gui.pauseButton.w*1.2,
	overY = gui.pauseButton.h*1.2,
	x = gui.pauseButton.x,
	y = gui.pauseButton.y,
	
	onRelease = function()
		local g2 = require "popup.popupPause".new(onResumeFromPopup,onReplayButtonTap)
		local group2 = display.newGroup()
		group2:insert(g2)
		mainGroup:insert(group2)
		group2.y = -300
		transition.to(group2,{time = 1000,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic, onStart = onStartPopup })
	end
})
homeButtonGroup:insert(pauseButton)

backgroundButton[1] = display.newImageRect(stageButtonGroup,gui.leftButton.fn,gui.buttonPosition.w,gui.buttonPosition.h)
	backgroundButton[1].x = gui.leftButton.x
	backgroundButton[1].y = gui.leftButton.y
	backgroundButton[1].id = 1
-- backgroundButton[1]:addEventListener("touch",onTouchMoveButton)

backgroundButton[2] = display.newImageRect(stageButtonGroup,gui.centerButton.fn,gui.buttonPosition.w,gui.buttonPosition.h)
	backgroundButton[2].x = gui.centerButton.x
	backgroundButton[2].y = gui.centerButton.y
	backgroundButton[2].id = 2
-- backgroundButton[2]:addEventListener("touch",onTouchMoveButton)
	
backgroundButton[3] = display.newImageRect(stageButtonGroup,gui.rightButton.fn,gui.buttonPosition.w,gui.buttonPosition.h)
	backgroundButton[3].x = gui.rightButton.x
	backgroundButton[3].y = gui.rightButton.y
	backgroundButton[3].id = 3
-- backgroundButton[3]:addEventListener("touch",onTouchMoveButton)	

okImage = display.newImageRect(homeButtonGroup,gui.okImage.fn,gui.okImage.w,gui.okImage.h)
	okImage.x = gui.okImage.x
	okImage.y = gui.okImage.y
	okImage.alpha = 0

goodImage = display.newImageRect(homeButtonGroup,gui.goodImage.fn,gui.goodImage.w,gui.goodImage.h)
	goodImage.x = gui.goodImage.x
	goodImage.y = gui.goodImage.y
	goodImage.alpha = 0

perfectImage = display.newImageRect(homeButtonGroup,gui.perfectImage.fn,gui.perfectImage.w,gui.perfectImage.h)
	perfectImage.x = gui.perfectImage.x
	perfectImage.y = gui.perfectImage.y
	perfectImage.alpha = 0
end
mainGroup:insert(backgroundGroup)
mainGroup:insert(stageButtonGroup)
mainGroup:insert(generateItemsGroup)
mainGroup:insert(homeButtonGroup)

do ------------------------------------ text -----------------
readyText = display.newText(mainGroup, "2",160 , 150, gui.timer.font, gui.timer.fontSize+20)
	readyText:setTextColor(255,0,0)
	readyText.alpha = 0
-- goText = display.newText(mainGroup, "GO", 160 -30, 150, gui.timer.font, gui.timer.fontSize+20)
	-- goText:setTextColor(255,0,0)
	-- goText.alpha = 0
goText = display.newImageRect(mainGroup,gui.goImage.fn,gui.goImage.w,gui.goImage.h)
	goText.x = gui.goImage.x
	goText.y = gui.goImage.y
	goText.alpha = 0
	
------------------------------- score -------------------------------
scoreText = display.newText(gui.score.text, gui.score.left, gui.score.top, gui.score.font, gui.score.fontSize)
	scoreText:setTextColor(gui.score.red, gui.score.green, gui.score.red, gui.score.alpha)
	scoreText.x = gui.score.x
	scoreText.y = gui.score.y
	scoreText.alpha = 0
homeButtonGroup:insert(scoreText)
end
------------------------------------- run test --------------------------------------
init()

----------------------------- end run test ------------------------------------------------
end




-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
		
	--	INSERT code here (e.g. start timers, load audio, start listeners, etc.)
	
	-----------------------------------------------------------------------------
	
end


-- Called when scene is about to move offscreen:
function scene:exitScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. stop timers, remove listeners, unload sounds, etc.)
	
	-----------------------------------------------------------------------------
	
end


-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. remove listeners, widgets, save state, etc.)
	
	-----------------------------------------------------------------------------
	
end

---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )

-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )

-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )

-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )

---------------------------------------------------------------------------------

return scene